<?php
namespace Orx\Mailer\MailBox\Message;
/**
 * Message Attachements.
 *
 * It represant a message attachement, the attachement is store in the DB in a basa64 encoding type
 *
 * @author Xavier VILAIN
 * @package Hive
 * @property int 		$messageid	 		Unique Message id
 * @property int		$attachementid		Attachement id
 * @property string	 	$name				File name 
 * @property int 		$encoding	 		Encoding Mode
 * @property datetime 	$charset			Charset
 * @property string 	$content			Encoded File content

 * 
 * @method array message()
 */
class Attachement extends \Fox\Object {
	
	/**
	 * Link to email
	 * @var string
	 */
	const LINK_MESSAGE = 'message';
	
	/**
	 * File Extension
	 * @return string
	 */
	public function type() {
		$parts = explode('.',$this->filename);
		if(count($parts) > 1) {
			return $parts[count($parts) - 1];
		} else {
			return 'unknown_extension';
		}
	}
	
	/**
	 * 
	 * Create the file on the server and donwload it to the client
	 * @return void
	 */
	public function download() {

		$fileFullName = $this->location().$this->cleanFileName();
		// Test to ensure that the file exists.
		if(!file_exists($fileFullName)) {
			$this->generateFile();
		}
		// Extract the type of file which will be sent to the browser as a header
		$type = filetype($fileFullName);
		$size = filesize($fileFullName);
		// Send file headers
		header('Pragma: public');
		header('Expires: 0');
		header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
		header('Cache-Control: private',false);
		header("Content-Type: $type" );
		header("Content-Disposition: attachment;filename=\"" .basename($this->filename) . "\"");
		header("Content-Transfer-Encoding:* binary");
		header("Content-Length: ".$size);
		// Send the file contents.
		set_time_limit(0);
		readfile($fileFullName);
	}
	
	/** 
	 * Preview the file directly in the browser
	 * @return void
	 */
	public function preview() {
		//@TODO
	}
	
	/**
	 * Clean File Name
	 * @return string
	 */
	public function cleanFileName() {
		$filename = time().'__'.$this->filename;
		return \Fox\Utilities\File::cleanUp($filename);
	}
	
	/**
	 * 
	 * Get decoded content
	 * @return string
	 */
	public function content() {
		if($this->encoding == 'base64') {
			return base64_decode($this->content);
		} 
		return $this->content;
	}
	
	/**
	 * Generate File on the server
	 * @retur bool
	 */
	public function generateFile() {
		$filename = $this->location().$this->cleanFileName();
		// Generate File on the server
		$fileContent = $this->content();
	    $fhandle = fopen($filename, 'w');
	    fwrite($fhandle, $fileContent);
	    fclose($fhandle);
	}
	
	/**
	 * Attachements Location
	 * @return string
	 */
	public function location() {
		$directory = _TEMP_.DIRECTORY_SEPARATOR.'messages'.DIRECTORY_SEPARATOR;
		// Create the file on the server
		if(!is_dir($directory)) {
			mkdir($directory);
		}
		return $directory;
	}
	
	/**
	 * 
	 * Check if the extension can be downloaded on the server
	 * @return bool
	 */
	public function authorizedExtension() {
		$authorized = array('jpeg','jpg','gif','png','bmp','doc','docx','pdf','rtf','ppt','xls','xlsx','csv');
		$extension = $this->extension();
		if(in_array($extension,$authorized)) {
			return true;
		}
		return false;
	}
	
	/**
	 * Get Attachement extension
	 * @return string
	 */
	public function extension() {
		$parts = explode('.',$this->filename);
		if(count($parts) > 1) {
			return strtolower($parts[count($parts)-1]);
		} else {
			return 'unknown';
		}
	}
}
\Fox\Dao::infos(Attachement::className(),new \Fox\Object\Info('message_attachements', \Fox\Databases::DB_APP))
->addAutoIncrementField('attachementid');